package com.ruizhong.centercontroll.util;

import com.ruizhong.centercontroll.server.WebSocketServer;

import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class SmoothValueTransition {
    private double value = 0; // 当前值
    private double targetValue; // 目标值
    private long transitionDuration; // 缓冲时间（毫秒）
    private long startTime; // 过渡开始时间
    private WSResult<HashMap<String, Object>> wsResult;
    private ExecutorService executorService;


    public SmoothValueTransition() {

    }

    /**
     * 开始平滑过渡
     *  @param a              初始值
     * @param b              目标值
     * @param transitionTime 过渡时间（毫秒）
     * @param variableMap
     */
    public void startSmoothTransition(double a, double b, long transitionTime, String wsToken, String beChangedVariableName, Map<String, Object> variableMap) {
        wsResult = new WSResult<>();
        executorService = Executors.newSingleThreadExecutor();
        value = a; // 设置初始值
        targetValue = b; // 设置目标值
        transitionDuration = transitionTime; // 设置过渡时间
        startTime = System.currentTimeMillis(); // 记录开始时间
        HashMap<String, Object> presetMessageMap = new HashMap<>();
        // 创建一个单线程的调度执行器
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        presetMessageMap.put("type", "presetMessage");
        presetMessageMap.put("key", beChangedVariableName);
        // 每隔一段时间更新值
        scheduler.scheduleAtFixedRate(() -> {
            long elapsedTime = System.currentTimeMillis() - startTime; // 已过时间
            if (elapsedTime >= transitionDuration) {
                value = targetValue; // 过渡完成，直接设置为目标值
                System.out.println("过渡完成，当前值: " + value);

                scheduler.shutdown(); // 关闭调度器
            } else {
                // 计算当前值（线性插值）
                double progress = (double) elapsedTime / transitionDuration;
                value = a + (b - a) * progress;
                System.out.println("当前值: " + value);
            }
            executorService.submit(() -> {
                presetMessageMap.put("data", value);
                wsResult.setData(presetMessageMap);
                try {
                    WebSocketServer.sendInfo(wsResult, wsToken);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (EncodeException e) {
                    e.printStackTrace();
                }
            });
            if (elapsedTime >= transitionDuration){
                executorService.shutdown();
                executorService = null;
                variableMap.put(beChangedVariableName,targetValue);
            }
        }, 0, 16, TimeUnit.MILLISECONDS); // 每隔16毫秒更新一次（约60帧/秒）
    }
}